package io.github.leon406.view.textview

import android.content.Context
import android.graphics.Color
import android.text.Spannable
import android.text.method.LinkMovementMethod
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatTextView
import io.github.leon406.view.span.LinkTouchMovementMethod

/** url/ e-mail / phone */
open class SpanTouchTextView
@JvmOverloads
constructor(
    context: Context,
    attributes: AttributeSet? = null,
    defaultStyle: Int = 0,
) : AppCompatTextView(context, attributes, defaultStyle), ISpanTouch {
    override var isTouchSpanHit: Boolean = false
        set(value) {
            if (value != field) {
                field = value
                isPressed = pressState
            }
        }

    override fun setPressed(pressed: Boolean) {
        pressState = pressed
        if (!isTouchSpanHit) {
            super.setPressed(pressed)
        }
    }

    private var pressState = false
    var isForceEventToParent = false
        set(value) {
            field = value
            isFocusable = !value
            isClickable = !value
            isLongClickable = !value
        }

    init {
        highlightColor = Color.TRANSPARENT
    }

    fun setMovementMethodDefault() {
        movementMethod = LinkTouchMovementMethod.instance
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (text !is Spannable || movementMethod !is LinkMovementMethod) {
            isTouchSpanHit = false
            return super.onTouchEvent(event)
        }
        isTouchSpanHit = true
        val re = super.onTouchEvent(event)
        if (isForceEventToParent) return isTouchSpanHit
        return re
    }

    override fun performClick(): Boolean {

        return if (!isTouchSpanHit && !isForceEventToParent) super.performClick() else false
    }

    override fun performLongClick(): Boolean {
        return if (!isTouchSpanHit && !isForceEventToParent) super.performLongClick() else false
    }
}
